import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet("/list_book")
public class ListBook extends HttpServlet {

    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/linux_exam?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "1qaz@WSX#EDC";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有来源跨域
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的方法
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); // 允许的请求头
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            // 准备SQL语句
            String sql = "SELECT * FROM t_book";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {

                // 执行查询
                ResultSet rs = pstmt.executeQuery();
                JSONArray books = new JSONArray();
                while (rs.next()) {
                    JSONObject book = new JSONObject();
                    book.put("number", rs.getString("number"));
                    book.put("name", rs.getString("name"));
                    book.put("author", rs.getString("author"));
                    books.put(book);
                }
                out.println(books.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("{\"error\": \"数据库错误: " + e.getMessage() + "\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"服务器内部错误\"}");
        }
    }
}
